package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseSelectObject;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.LocaleWorkQueryCount;
import com.isunland.managesystem.entity.LocaleWorkQueryCountSub;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.MultiLinesView;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.UUID;

import static com.isunland.managesystem.common.ApiConst.URL_DELETE_LOCALEWORKQUERYCOUNTSUB;
import static com.isunland.managesystem.common.ApiConst.URL_UPDATE_LOCALEWORKQUERYCOUNTSUB;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/4/8 16:03
 */
public class LocaleWorkQueryCountSubDetailFragment extends BaseFragment
    implements View.OnClickListener {
  public static final String EXTRA_MAIN_ITEM =
      LocaleWorkQueryCountSubDetailFragment.class.getSimpleName() + "EXTRA_MAIN_ITEM";
  public static final String EXTRA_ITEM =
      LocaleWorkQueryCountSubDetailFragment.class.getSimpleName() + "EXTRA_ITEM";
  public static final String EXTRA_TYPE =
      LocaleWorkQueryCountSubDetailFragment.class.getSimpleName() + "EXTRA_TYPE";
  public static final int TYPE_DETAIL = 1;
  public static final int TYPE_ADD = 2;
  public static final int TYPE_EDIT = 3;
  private static final int REQUEST_STAFF = 1;
  private static final int REQUEST_DEVICE = 2;
  private static final int REQUEST_ALTER = 3;
  @BindView(R.id.sl_workStaffName) SingleLineView mSlWorkStaffName;
  @BindView(R.id.sl_deviceCode) SingleLineView mSlDeviceCode;
  @BindView(R.id.sl_deviceNo_LocaleWorkQueryCountSub) SingleLineView
      mSlDeviceNoLocaleWorkQueryCountSub;
  @BindView(R.id.sl_workDesc) MultiLinesView mSlWorkDesc;
  @BindView(R.id.sl_workMuch) SingleLineView mSlWorkMuch;
  @BindView(R.id.sl_workMunit) SingleLineView mSlWorkMunit;

  private View mView;
  private int mType;
  private LocaleWorkQueryCountSub mItem;
  private LocaleWorkQueryCount mItemMain;
  private String mStaffCode;
  private ArrayList<BaseSelectObject> mStaffList;
  private ArrayList<BaseSelectObject> mDeviceList;

  public static Fragment newInstance(LocaleWorkQueryCount itemMain, LocaleWorkQueryCountSub item,
      int typeCode) {
    LocaleWorkQueryCountSubDetailFragment fragment = new LocaleWorkQueryCountSubDetailFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_MAIN_ITEM, itemMain);
    args.putSerializable(EXTRA_ITEM, item);
    args.putInt(EXTRA_TYPE, typeCode);
    fragment.setArguments(args);
    return fragment;
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    initData();
    initView(inflater, container, savedInstanceState);
    ButterKnife.bind(this, mView);
    return mView;
  }

  @SuppressWarnings("all")
  private void initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mView =
        inflater.inflate(R.layout.fragment_locale_work_query_count_sub_detail, container, false);
    ButterKnife.bind(this, mView);
    setTitleCustom(MyStringUtil.connect(R.string.localeWorkQueryCountSub));

    //赋值
    if (mType == TYPE_ADD || mItemMain != null) {
      mSlWorkMunit.setTextContent(mItemMain.getWorkMunit());
    }
    if ((mType == TYPE_DETAIL || mType == TYPE_EDIT) && mItem != null) {
      mSlDeviceCode.setTextContent(mItem.getDeviceCode());
      mSlDeviceNoLocaleWorkQueryCountSub.setTextContent(mItem.getDeviceNo());
      mSlWorkDesc.setTextContent(mItem.getWorkDesc());
      mSlWorkMuch.setTextContent(mItem.getWorkMuch());
      mSlWorkMunit.setTextContent(mItem.getWorkMunit());
      mSlWorkStaffName.setTextContent(mItem.getWorkStaffName());
      mStaffCode = mItem.getWorkStaffCode();
    }
    //设置点击事件
    if (mType == TYPE_ADD || mType == TYPE_EDIT) {
      mStaffList = getStaff();
      mDeviceList = getDevice();
      mSlWorkStaffName.setOnClickContentListener(this);
      mSlDeviceCode.setOnClickContentListener(this);
    }
    //详情不可编辑
    if (mType == TYPE_DETAIL) {
      mSlDeviceCode.setInputEnabled(false);
      mSlDeviceNoLocaleWorkQueryCountSub.setInputEnabled(false);
      mSlWorkDesc.setInputEnabled(false);
      mSlWorkMuch.setInputEnabled(false);
      mSlWorkMunit.setInputEnabled(false);
      mSlWorkStaffName.setInputEnabled(false);
    }
  }

  public void initData() {
    if (getArguments() != null) {
      mType = getArguments().getInt(EXTRA_TYPE, 0);
      mItemMain = (LocaleWorkQueryCount) getArguments().getSerializable(EXTRA_MAIN_ITEM);
      mItem = (LocaleWorkQueryCountSub) getArguments().getSerializable(EXTRA_ITEM);
    }
  }

  @Override public void onClick(View v) {
    if (!(v.getTag() instanceof Integer)) return;
    int id = (int) v.getTag();
    if (id == R.id.sl_deviceCode) {
      selectDevice();
    }
    if (id == R.id.sl_workStaffName) {
      selectStaff();
    }
  }

  private void selectDevice() {
    if (mDeviceList == null) return;
    DialogFragment dialog = SimpleArrayDialogFragment.newInstance(mDeviceList);
    dialog.setTargetFragment(this, REQUEST_DEVICE);
    dialog.show(mActivity.getSupportFragmentManager(), "");
  }

  private void selectStaff() {
    if (mStaffList == null) return;
    DialogFragment dialog = SimpleArrayDialogFragment.newInstance(mStaffList);
    dialog.setTargetFragment(this, REQUEST_STAFF);
    dialog.show(mActivity.getSupportFragmentManager(), "");
  }

  private ArrayList<BaseSelectObject> getStaff() {
    if (mItemMain == null) return null;
    ArrayList<String> nameList =
        MyStringUtil.splitStr(mItemMain.getWorkernames(), getString(R.string.comma));
    ArrayList<String> jobNoList =
        MyStringUtil.splitStr(mItemMain.getWorkerids(), getString(R.string.comma));
    if (nameList == null || nameList.size() == 0) return null;
    if (jobNoList == null || jobNoList.size() == 0) return null;
    if (nameList.size() != jobNoList.size()) return null;
    ArrayList<BaseSelectObject> list = new ArrayList<>();
    for (int i = 0; i < nameList.size(); i++) {
      list.add(new BaseSelectObject(jobNoList.get(i), nameList.get(i), ""));
    }
    return list;
  }

  private ArrayList<BaseSelectObject> getDevice() {
    if (mItemMain == null) return null;
    ArrayList<String> deviceCodeList =
        MyStringUtil.splitStr(mItemMain.getDevicecode(), getString(R.string.comma));
    ArrayList<String> deviceNoList =
        MyStringUtil.splitStr(mItemMain.getDeviceNo(), getString(R.string.comma));
    if (deviceCodeList == null || deviceCodeList.size() == 0) return null;
    if (deviceNoList == null || deviceNoList.size() == 0) return null;
    if (deviceCodeList.size() != deviceNoList.size()) return null;
    ArrayList<BaseSelectObject> list = new ArrayList<>();
    for (int i = 0; i < deviceNoList.size(); i++) {
      list.add(new BaseSelectObject(deviceNoList.get(i), deviceCodeList.get(i), ""));
    }
    return list;
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_STAFF && data != null) {
      BaseSelectObject result =
          (BaseSelectObject) data.getSerializableExtra(SimpleArrayDialogFragment.EXTRA_VALUE);
      if (result == null) return;
      mSlWorkStaffName.setTextContent(result.getName());
      mStaffCode = result.getId();
    }
    if (requestCode == REQUEST_DEVICE && data != null) {
      BaseSelectObject result =
          (BaseSelectObject) data.getSerializableExtra(SimpleArrayDialogFragment.EXTRA_VALUE);
      if (result == null) return;
      mSlDeviceCode.setTextContent(result.getName());
      mSlDeviceNoLocaleWorkQueryCountSub.setTextContent(result.getId());
    }
    //修改完成,通知列表更新
    if (requestCode == REQUEST_ALTER) {
      mActivity.setResult(Activity.RESULT_OK);
      mActivity.finish();
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (mType == TYPE_ADD || mType == TYPE_EDIT) {
      inflater.inflate(R.menu.menu_confirm, menu);
    }
    if (mType == TYPE_DETAIL) {
      inflater.inflate(R.menu.menu_alter_delete, menu);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_confirm:
        volleyPostConfirm();
        return true;
      case R.id.menu_item_alter:
        LocaleWorkQueryCountSubDetailActivity.newInstance(this, mActivity, REQUEST_ALTER, mItemMain,
            mItem, TYPE_EDIT);
        return true;
      case R.id.menu_item_delete:
        volleyPostDelete();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(URL_DELETE_LOCALEWORKQUERYCOUNTSUB);
    ParamsNotEmpty params = new ParamsNotEmpty();
    if (mItem == null) return;
    params.put("id", mItem.getId());
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) {
        Base original = new Gson().fromJson(json, Base.class);
        ToastUtil.show(original.getMessage());
        if (original.getResult() == Base.SUCCESS) {
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        }
      }
    });
  }

  private void volleyPostConfirm() {

    if (mSlDeviceCode.isEmptyContent()
        || mSlDeviceNoLocaleWorkQueryCountSub.isEmptyContent()
        || mSlWorkStaffName.isEmptyContent()
        || mSlWorkMuch.isEmptyContent()) {
      ToastUtil.show(R.string.completeWrite);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(URL_UPDATE_LOCALEWORKQUERYCOUNTSUB);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainId", mItemMain == null ? "" : mItemMain.getId());
    params.put("id", mItem == null ? UUID.randomUUID().toString() : mItem.getId());
    params.put("workStaffCode", mStaffCode);
    params.put("workStaffName", mSlWorkStaffName.getTextContent());
    params.put("deviceCode", mSlDeviceCode.getTextContent());
    params.put("deviceNo", mSlDeviceNoLocaleWorkQueryCountSub.getTextContent());
    params.put("workDesc", mSlWorkDesc.getTextContent());
    params.put("workMuch", mSlWorkMuch.getTextContent());
    params.put("workMunit", mSlWorkMunit.getTextContent());
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) {
        Base original = new Gson().fromJson(json, Base.class);
        ToastUtil.show(original.getMessage());
        if (original.getResult() == Base.SUCCESS) {
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        }
      }
    });
  }
}
